
if (sessionStorage.getItem('MyApply_curr') != null) {
    sessionStorage.setItem('MyApply_curr',1)
}
function creatCompare(propertyName) {
    return function (obj1, obj2) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if (value1 > value2) {
            return -1
        } else if (value1 < value2) {
            return 1
        } else {
            return 0
        }
    }
}
//填充我的申请表格
function initTable(data) {
    colType = $("#serverType").val()
    appType = $("#applyType").val()
    appStatus = $("#applyStatus").val()
    ipt_collect_date = $('#ipt_date').val();
    ipt_collect_name = $('#ipt_search').val();
    var tdata = dealData(data);  
    tdata.sort(creatCompare("APPLY_TIME")) 
    table.render({
        elem: '#applyTable'
        , data: tdata
      , toolbar: true 
      , toolbar: '#tbApplyToolBar'   //这里在左边显示，然后指定到模版id
      ,defaultToolbar: [] 
      ,page: {
        limit:20,
        curr:sessionStorage.getItem('MyApply_curr') ? sessionStorage.getItem('MyApply_curr') : 1
        }
      , cols: [[
          { type: 'numbers', title: '序号', align: 'center', width: 100 }
          , { field: 'NAME', title: '服务名称', align: 'center' }
          , { field: 'SERVERTYPE', title: '服务类型', align: 'center' }
          , { field: 'APPLYTYPE', title: '申请类型', align: 'center' }
          , { field: 'APPLY_TIME', title: '申请时间', align: 'center' }
          , { field: 'checkStatus', title: '审核状态', align: 'center' }
          , { field: 'checkResult', title: '审核结论', align: 'center'}
          , { align: 'center', title: '权限操作', toolbar: '#apply-table-operate' }
          , { align: 'center', title: '操作', toolbar: '#apply-table-operate2' }
      ]]
      , response: {
          statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
      }
      , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
          return {
              "code": res.status, //解析接口状态
              "msg": res.message, //解析提示文本
              "count": res.total, //解析数据长度
              "data": res.rows.item //解析数据列表
          };
      }
      , done: function (res, curr, count) {
        sessionStorage.setItem('MyApply_curr',curr)
          $("[data-field = 'SERVERTYPE']").children().each(function () {
              for (var key in serverTypes) {
                  var oneData = serverTypes[key];
                  if ($(this).text() == "" + oneData.ZDVALUE + "") {
                      $(this).text(oneData.ZDTITLE);
                  }
              }
          });
          $("[data-field = 'APPLYTYPE']").children().each(function () {
            for (var key in applyTypes) {
                var oneData = applyTypes[key];
                if ($(this).text() == "" + oneData.ZDVALUE + "") {
                    $(this).text(oneData.ZDTITLE);
                }
            }
        });
        $("[data-field = 'checkStatus']").children().each(function () {
            for (var key in applyStatus) {
                var oneData = applyStatus[key];
                if ($(this).text() == "" + oneData.ZDVALUE + "") {
                    $(this).text(oneData.ZDTITLE);
                }
            }
        });
        $("[data-field = 'checkResult']").children().each(function () {
            for (var key in applyResults) {
                var oneData = applyResults[key];
                if ($(this).text() == "" + oneData.ZDVALUE + "") {
                    $(this).text(oneData.ZDTITLE);
                }
            }
        });
      }
    });
    initDropdown();
    $("#serverType").val(colType);
    $("#applyType").val(appType);
    $("#applyStatus").val(appStatus);
    $('#ipt_date').val(ipt_collect_date);
    $('#ipt_search').val(ipt_collect_name);
    layui.form.render('select');
    //日期时间范围
    laydate.render({
        elem: '#ipt_date'
    , type: 'date'
    , range: true
    });
}
//模糊查询
function searchData(){
    var searchFormData = form.val('ApplyForm');
    var res = getTbData(searchFormData);  
    sessionStorage.setItem('MyApply_curr',1) 
    if (res != null) {
        initTable(res);
    } 
}
//获取表格数据
function getTbData(obj){
    var data = {};
    var startTime,endTime;
    if(obj){
        if(isNull(obj.serverType)){
            obj.serverType = "ALL"
        }else{
            if(obj.serverType == "1"){
                if(!isNull(obj.applyStatus)){
                    if(obj.applyStatus == "0"){
                        obj.applyStatus ="1"
                    }else if(obj.applyStatus == "1"){
                        obj.applyStatus ="2"
                    }else if(obj.applyStatus == "2"){
                        obj.applyStatus ="3"
                    }
                }
            }
        }
        if(!isNull(obj.ipt_date)){
            startTime = $.trim(obj.ipt_date.substring(0,10));
            endTime = $.trim(obj.ipt_date.substring(13));
        }
        data = {
            no:portaluserno,
            serviceType:obj.serverType,
            applyType:obj.applyType,
            startTime:startTime,
            endTime:endTime,
            applyStatus:obj.applyStatus,
            serverName:obj.ipt_search,
            applyType:$('#applyType').val() == "" ? 'ALL' : $('#applyType').val()
        }
    }else{
        data = {
            no:portaluserno,
            serviceType:"ALL",
            applyType:'ALL'
        }
    }
    var resultData = null;
    var results = sendAjax(modelURL + "resource/getMyApplys", "POST", data);
    if (results.code == 200) {
        resultData = results.data;
    }else{
        layui.layer.msg(results.msg,{icon:5})
    }
    return resultData;
}
//点击运行按钮
function runningApply(name){
    window.parent.window.parent.window.$(".layui-tab-title .layui-this").removeClass("layui-this");
    window.parent.window.parent.window.$(".layui-tab-title #header_tab2").addClass("layui-this");
    window.parent.window.parent.window.$("#applicationCenter").hide();
    window.parent.window.parent.window.$("#fmap").attr("src","/MapServer/Portal/3DViewer.html?mode=default");
    window.parent.window.parent.window.$("#fmap").show();
    window.parent.window.parent.window.$("#fmap").attr("jumpping2Tools",name);
}
//查看审核记录
function lookCheckRecording(obj){
    var results = null;
    var checkData,id;
    if(obj.data.APPLYTYPE == "1"){
        id = obj.data.APPLYRESOURCEID;
        $('#auditRecordsSH').html('服务注册申请') 
    } else if (obj.data.APPLYTYPE == "3") {
        id = obj.data.RESOURCEID; 
        $('#auditRecordsSH').html('服务注册申请') 
    } else{
        id = obj.data.ID;
        $('#auditRecordsSH').html('应用运行申请') 
    }
    results = sendAjax(modelURL + "resource/getApprovalMemo", "POST", {
        id: id,
        serviceType:obj.data.APPLYTYPE
    });
    if (results.code == 200) {
        checkData = results.data;
    }else{
        layer.msg("获取数据失败！",{icon:5});
    }
    $('#auditRecordsH3').html(obj.data.NAME) 
    
    /* 
    1 APPLY_TIME （checktime）  applyStatus = 2 
    2 APPLY_TIME （savedate） ishistory = 1  
    3 CHECKTIME （checktime） ishistory = 0
    */  
    let approvaldateTime 
    // 1 使用申请 2 运行申请 3 注册申请 
    if (obj.data.APPLYTYPE == 1) { 
        approvaldateTime = formatDate (checkData.approvalTime) //  new Date(checkData.approvalTime).toISOString().replace("T", " ").replace(".000Z", ""); 
        $('#auditRecordsSH').html('使用申请') 
        $('#auditRecordsYJ').html(checkData.approvalReason);
    } else if (obj.data.APPLYTYPE == 2) { 
        approvaldateTime = formatDate (checkData.approvaldate) //  new Date(checkData.approvaldate).toISOString().replace("T", " ").replace(".000Z", ""); 
        $('#auditRecordsSH').html('运行申请')  
        $('#auditRecordsYJ').html(checkData.opinion);
    } else if (obj.data.APPLYTYPE == 3) { 
        approvaldateTime = formatDate (checkData.checktime) //  new Date(checkData.checktime).toISOString().replace("T", " ").replace(".000Z", ""); 
        $('#auditRecordsSH').html('注册申请')   
        $('#auditRecordsYJ').html(checkData.checkinfo);
    } 

    $('#auditRecordsTime').html(approvaldateTime)
    if (checkData.checkresult == '1') {
        $('#rdoCheckResult').html('<input type="radio" value="1" title="通过" checked="">') 
    } else if (checkData.checkresult == '2') {
        $('#rdoCheckResult').html('<input type="radio" value="2" title="未通过" checked="">') 
    }
    // $('#auditRecordsYJ').html(checkData.opinion);
    form.render();
    layer.open({
        type: 1,
        title: "审核记录",
        offset: 'auto',
        shadeClose: true, //点击遮罩不关闭
        content: $("#historyCheckLayer"),
        btn: ['关闭'],
        yes: function(index, layero) {
            layer.close(index);
        }
    });
}
//删除数据
function deleteData(obj){
    var results = null;
    var id;
    if(obj.data.APPLYTYPE == "1"){
        id = obj.data.APPLYRESOURCEID;
    }else{
        id = obj.data.ID;
    }
    layer.confirm("确认要删除吗？", { title: "删除" }, 
    function (index){
        if (index) {
            results = sendAjax(modelURL + "resource/deleteApplyMemo", "POST", {
                id: id,
                serviceType:obj.data.APPLYTYPE
            });
            if (results.code == 200) {
                layer.msg("删除成功！",{icon:1});
                var TBData = getTbData();
                initTable(TBData)
            }else{
                layer.msg("删除失败！",{icon:5});
            }
            layer.close(index);
        }
    })
}
//对获取到的数据进行处理
function dealData(data){  
    data.map(function(item, index) {
        //APPLYTYPE服务类型 APPLYTYPE=1：数据服务 APPLYTYPE=2：应用服务
        //如果APPLYTYPE=1,则APPLY_STATUS=1:待审核;APPLY_STATUS=2:通过;APPLY_STATUS=3:不通过
        //如果APPLYTYPE=2,则APPLY_STATUS=0:待审核;APPLY_STATUS=1:通过;APPLY_STATUS=2:不通过
        if(item.APPLYTYPE == "1"){ 
            if(item.APPLY_STATUS == "1"){
                item.APPLY_STATUS = "0";
            }else if(item.APPLY_STATUS == "2"){
                item.APPLY_STATUS = "1";
            }else if(item.APPLY_STATUS == "3"){
                item.APPLY_STATUS = "2";
            }
        } 
        //checkStatus：申请状态，0：待审核 1：已审核
        //checkResult: 审核结果，1：通过 2：不通过
        if(item.APPLY_STATUS == "0"){
            item["checkStatus"] = "0"
            item["checkResult"] = "0";
        }else{
            item["checkStatus"] = "1"
            if(item.APPLY_STATUS == "1"){
                item["checkResult"] = "1";
            }else if(item.APPLY_STATUS == "2"){
                item["checkResult"] = "2";
            }
        }
        
        if(item.APPLY_TIME != ""){
            item.APPLY_TIME = formatDate(item.APPLY_TIME)
        }
        return item;
    }) 
    let newData = []
    data.map(item => {
        newData.push(Object.assign({}, item, { 
            SERVERTYPE:item.APPLYTYPE
        }))
    })
    
    return newData;
}
//获取下拉列表  ALL
function initDropdown() {  
    let resultsYSJ = sendAjax(modelURL + "dict/getDataDict", "POST", {
        name: 'MYAPPLYSTYPE'
    });
    if (resultsYSJ.code == 200) {
        resultsYSJ.data.map(item => {
            $('#applyType').append(`<option value="${item.ZDVALUE}" label="${item.ZDTITLE}">${item.ZDTITLE}</option>`)
        })
        layui.form.render("select");
    }
    for (var i = 0; i < newServerTypes.length; i++) {
        $("[name='serverType']").append("<option value='" + newServerTypes[i].ZDVALUE + "'>" + newServerTypes[i].ZDTITLE + "</option>");
    } 

    // for (var j = 0; j < applyTypes.length; j++) {
    //     $("[name='applyType']").append("<option value='" + applyTypes[j].ZDVALUE + "'>" + applyTypes[j].ZDTITLE + "</option>");
    // }
    for (var k = 0; k < applyStatusTop.length; k++) {
        $("[name='applyStatus']").append("<option value='" + applyStatusTop[k].ZDVALUE + "'>" + applyStatusTop[k].ZDTITLE + "</option>");
    }
    layui.form.on('select(serverTypeSelect)', function (data) {
        $("#serverType").val(data.value);
        colType = $("#serverType").val()
    });
    layui.form.on('select(applyTypeSelect)', function (data) {
        $("#applyType").val(data.value);
        appType = $("#applyType").val()
    });
    layui.form.on('select(applyStatusSelect)', function (data) {
        $("#applyStatus").val(data.value);
        appStatus = $("#applyStatus").val()
    });
}
//初始化下拉框数据 
// 申请类型 1 使用申请 2 运行申请 3 注册申请
function initDropdownData(){
    serverTypes = [{
        ZDTITLE: "数据服务",
        ZDVALUE: "1"
    },{
        ZDTITLE: "应用服务",
        ZDVALUE: "2"
    },{
        ZDTITLE: "数据服务",
        ZDVALUE: "3"
    }]; 

    newServerTypes = [{
        ZDTITLE: "数据服务",
        ZDVALUE: "1"
    },{
        ZDTITLE: "应用服务",
        ZDVALUE: "2"
    }];
    
    applyTypes = [{
        ZDTITLE: "使用申请",
        ZDVALUE: "1"
    },{
        ZDTITLE: "运行申请",
        ZDVALUE: "2"
    },{
        ZDTITLE: "注册申请",
        ZDVALUE: "3"
    }];
    applyStatusTop = [{
        ZDTITLE: "未审核",
        ZDVALUE: "0"
    },{
        ZDTITLE: "已通过",
        ZDVALUE: "1"
    },{
        ZDTITLE: "未通过",
        ZDVALUE: "2"
    }]
    applyStatus = [{
        ZDTITLE: "未审核",
        ZDVALUE: "0"
    },{
        ZDTITLE: "已审核",
        ZDVALUE: "1"
    }]
    applyResults = [
    {
        ZDTITLE: "待审核",
        ZDVALUE: "0"
    },
    {
        ZDTITLE: "已通过",
        ZDVALUE: "1"
    },{
        ZDTITLE: "未通过",
        ZDVALUE: "2"
    }]
}